package com.yuqiao.read.design.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * 天氣預報數據
 */
public class WeatherData implements ISubject {

    /**
     * 观察者集合
     */
    private List<IObserver> observerList;
    /**
     * 气温，湿度，气压
     */
    private float temp,humidity, pressure;

    /**
     * 创建观察者集合
     */
    public WeatherData(){
        observerList = new ArrayList<IObserver>();
    }

    /**
     * 注册观察者
     * @param observer
     */
    @Override
    public void registerObserver(IObserver observer) {
        observerList.add(observer);
    }

    /**
     * 移除某个观察者
     * @param observer
     */
    @Override
    public void removeObserver(IObserver observer) {
        int i = observerList.indexOf(observer);
        if(i>=0){
            observerList.remove(i);
        }
    }

    /**
     * 通知所有观察者
     */
    @Override
    public void notifyObservers() {
        if(!observerList.isEmpty())
        for(IObserver observer : observerList){
            observer.update(temp,humidity,pressure);
        }
    }

    void measurementsChanged(){
        notifyObservers();
    }

    /**
     * 更新并通知
     * @param temp
     * @param humidity
     * @param pressure
     */
    public void setMeasurements(float temp,float humidity,float pressure){
        this.temp = temp;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }
}
